from django.db import models
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser,PermissionsMixin
)

# Create your models here.



class UserProfileManager(BaseUserManager):
    def create_user(self, email, name, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            name=name,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            name=name,
        )
        user.is_superuser = True
        user.save(using=self._db)
        return user


class UserProfile(AbstractBaseUser,PermissionsMixin):
    """堡垒机账号"""
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,

    )
    name = models.CharField(max_length=64, verbose_name="姓名")
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)
    objects = UserProfileManager()

    host_to_remote_users = models.ManyToManyField("User_to_Host")
    host_groups = models.ManyToManyField("HostGroup")

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

# Create your models here.
class Idc(models.Model):
    name=models.CharField(max_length=64,unique=True,verbose_name='机房名称')
    def __str__(self):
        return self.name

class Host(models.Model):
    idc=models.ForeignKey('Idc',verbose_name='机房')
    name=models.CharField(max_length=64,unique=True,verbose_name='主机名称')
    ip=models.GenericIPAddressField(verbose_name='ip地址')
    port=models.SmallIntegerField(verbose_name='端口')



    def __str__(self):
        return self.name

class HostGroup(models.Model):
    name=models.CharField(max_length=64,verbose_name='组名称')
    host_to_remote_users=models.ManyToManyField('User_to_Host')

    def __str__(self):
        return self.name


class Remote_User(models.Model):
    '''
    服务器上真实明文用户名和密码
    '''
    username=models.CharField(max_length=64,verbose_name='用户名')
    password=models.CharField(max_length=128,verbose_name='用户密码')
    class Meta:
        unique_together=('username','password',)
    def __str__(self):
        return '%s %s'%(self.username,self.password)

class User_to_Host(models.Model):
    host=models.ForeignKey('Host',verbose_name='主机')
    userinfo=models.ForeignKey('Remote_User',verbose_name='服务器真实用户信息')

    def __str__(self):
        return self.host.name

class Audit_Log(models.Model):
    user=models.ForeignKey('UserProfile',verbose_name='操作用户')
    remote_user=models.ForeignKey('Remote_User',verbose_name='服务器真实用户密码')
    log_type_choices=(
        (0,'登陆'),
        (1,'操作'),
        (2,'退出')
    )
    log_type=models.SmallIntegerField(choices=log_type_choices)
    command=models.CharField(max_length=255,verbose_name='操作命令',null=True,blank=True)
    date=models.DateField(auto_now_add=True,verbose_name='操作日期')

    def __str__(self):
        return "用户:%s,类型:%s"%(self.user,self.get_log_type_display())

class Task(models.Model):
    content=models.CharField(max_length=64)
    type_choices=(
        ('cmd','远程命令'),
        ('file','文件传输')
    )
    type=models.CharField(choices=type_choices,max_length=64)
    user=models.ForeignKey('UserProfile')
    date=models.DateField(auto_now_add=True)

    def __str__(self):
        return self.content

class Task_res(models.Model):
    task=models.ForeignKey('Task')
    status_choices=(
        (0,'初始化'),
        (1,'成功'),
        (2,'失败'),
        (3,'超时'),
        (4,'执行中'),
    )
    status=models.SmallIntegerField(choices=status_choices)
    host=models.ForeignKey('User_to_Host')
    res=models.TextField()
    data=models.DateField(auto_now_add=True)
    def __str__(self):
        return '任务：%s ,状态：%s'%(self.task.content,self.get_status_display())